package net.csdn.business.notify.common.domain;

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

/**
 * @ClassName MdcTaskDecorator
 * @Description 异步方法会开启一个新线程，我们想要是异步方法和主线程共用同一个traceId，任务适配器MdcTaskDecorator
 * @Author zhangyl
 * @Date 2023/8/12 17:47
 */
public class CustomTaskDecorator implements TaskDecorator {
    /**
     * 使异步线程池获得主线程的上下文
     * @param runnable
     * @return
     */
    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String,String> map = MDC.getCopyOfContextMap();
       /* AuthContext authContext=AuthContextHolder.getContext();*/
        return () -> {
            try{
                /*AuthContextHolder.setContext(authContext);*/
                if(map==null){
                    MDC.clear();
                }else{
                    MDC.setContextMap(map);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
